import socket
import string

class socks:

  def __init__(self, sock=None, msglen=1024):
    if sock is None:
      self.sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
    else:
      self.sock = sock
    self.socklen = msglen

  def myconnect(self, host, port):
    self.sock.connect((host, port))

  def send(self, smsg):
    totalsent = 0
    while totalsent < self.socklen:
      sent = self.sock.send(smsg[totalsent:])
      if sent == 0: raise RuntimeError("Socket connection broken")
      totalsent = totalsent + sent

  def myreceive(self ):
    rmsg = ''
    while len(rmsg) < self.socklen:
      rchunk = self.sock.recv(self.socklen - len(rmsg))
      if rchunk == '': raise RuntimeError("Socket connection broken")
      rmsg = rmsg + rchunk
      if string.find(rchunk, "\n") == len(rchunk)-1: return rmsg
    return rmsg
